package com.cjc.sport.controller.admin;

//import com.cjc.sport.entity.*;

import com.cjc.sport.controller.BaseController;
import com.cjc.sport.entity.Course;
import com.cjc.sport.entity.NumEnum;
import com.cjc.sport.entity.ReturnJson;
import com.cjc.sport.entity.SortObject;
import com.cjc.sport.entity.SelectCourse;
import com.cjc.sport.entity.EnumValidation;
import com.cjc.sport.exception.CourseException;
import com.cjc.sport.exception.ServiceException;
import com.cjc.sport.mapper.CourseMapper;
import com.cjc.sport.service.CourseService;
import com.cjc.sport.util.SportUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.ValidationException;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import java.util.UUID;

/**
 * 管理课程表控制层
 *
 * @Author: Bruse Queen
 * @Date: 2018/2/28
 */
@RestController
@CrossOrigin
public class CourseController extends BaseController {
    /**
     * 日志配置
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(CourseController.class);
    /**
     * 装配课程表服务层
     */
    @Autowired
    private CourseService courseService;

    /**
     * 统一返回对象
     */
    private ReturnJson result;
    /**
     * 装配课程mapper
     */
    @Autowired
    private CourseMapper courseMapper;
    /**
     * 获取配置文件
     */
    private Environment environment;


    /**
     * 添加序号校验（2018-3-12）
     */

    /**
     * 检查是否存在序号
     *
     * @param request 请求头
     * @return ReturnJson 返回封装的Json对象
     */
    @RequestMapping(value = "/admin/checkCourseAdd", method = RequestMethod.POST)
    public ReturnJson checkCourseAdd(HttpServletRequest request) {
        try {

            JsonObject jsonObject = getJsonObject(request);
            String categoryName = jsonObject.has("categoryName")
                    ? jsonObject.get("categoryName").getAsString() : "0";
            int courseNum = jsonObject.has("courseNum")
                    ? jsonObject.get("courseNum").getAsInt() : 0;

            Course course = courseMapper.selectCourse(categoryName, courseNum);

            if (null == course) {
                result = new ReturnJson(NumEnum.SUCCESS.getIndex(), "可以添加此序号！");
            } else {
                String tempCategoryName = course.getCategoryName();
                result = new ReturnJson(NumEnum.FAIL.getIndex(), "已有此序号！");
            }
        } catch (Exception e) {
            LOGGER.error("CourseController--checkCourseAdd error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), e.getMessage());
        }
        return result;
    }

    /**
     * 检查是否存在序号
     *
     * @param request 请求头
     * @return ReturnJson 返回封装的Json对象
     */
    @RequestMapping(value = "/admin/checkCourseUpdate", method = RequestMethod.POST)
    public ReturnJson checkCourseUpdate(HttpServletRequest request) {
        try {

            JsonObject jsonObject = getJsonObject(request);
            String courseId = jsonObject.has("courseId")
                    ? jsonObject.get("courseId").getAsString() : "0";
            String categoryName = jsonObject.has("categoryName")
                    ? jsonObject.get("categoryName").getAsString() : "0";
            int courseNum = jsonObject.has("courseNum")
                    ? jsonObject.get("courseNum").getAsInt() : 0;
            Course tempCourse = courseMapper.selectCourse(categoryName, courseNum);

            if (null != tempCourse && !tempCourse.getCourseId().equals(courseId)) {
                result = new ReturnJson(NumEnum.FAIL.getIndex(), "已有此序号！");
            } else {
                result = new ReturnJson(NumEnum.SUCCESS.getIndex(), "可以修改此序号！");
            }
        } catch (Exception e) {
            LOGGER.error("CourseController--checkCourseUpdate error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), e.getMessage());
        }
        return result;
    }

    /**
     * 新增课程
     *
     * @param course 课程表对象
     * @return ReturnJson 返回封装的Json对象
     */
    @RequestMapping(value = "/admin/addCourse", method = RequestMethod.POST)
    public ReturnJson addCourse(@RequestBody @Valid Course course) {
        try {
            // 处理数据
            Course courseTemp = SportUtils.removeSpaceForCourse(course);
            // 执行新增
            courseService.addCourse(courseTemp);
            result = new ReturnJson(NumEnum.SUCCESS.getIndex(), "保存数据成功！");

        } catch (CourseException c) {
            LOGGER.error("CourseController--addCourse error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), c.getMessage());
        } catch (Exception e) {
            LOGGER.error("CourseController--addCourse error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), e.getMessage());
        }
        return result;
    }

    /**
     * 编辑课程
     *
     * @param course 课程表对象
     * @return ReturnJson 返回封装的Json对象
     */
    @RequestMapping(value = "/admin/updateCourse", method = RequestMethod.POST)
    public ReturnJson updateCourse(@RequestBody @Valid Course course) {
        try {
            // 校验字段
            if (SportUtils.judgeNull(course.getCourseId().trim())
                    || course.getCourseId().length() > EnumValidation.FOURTY.getNum()) {
                throw new ValidationException("请输入合法的课程ID!");
            }
            // 规整
            course.setCourseId(course.getCourseId().trim());
            // 处理数据
            Course courseTemp = SportUtils.removeSpaceForCourse(course);
            // 执行编辑
            courseService.updateCourse(courseTemp);
            result = new ReturnJson(NumEnum.SUCCESS.getIndex(), "保存数据成功！");

        } catch (CourseException c) {
            LOGGER.error("CourseController--updateCourse error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), c.getMessage());
        } catch (ValidationException v) {
            LOGGER.error("CourseController--updateCourse error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), v.getMessage());
        } catch (Exception e) {
            LOGGER.error("CourseController--updateCourse error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), e.getMessage());
        }
        return result;
    }

    /**
     * 删除课程
     *
     * @param course 课程表对象
     * @return ReturnJson 返回封装的Json对象
     */
    @RequestMapping(value = "/admin/deleteCourse", method = RequestMethod.POST)
    public ReturnJson deleteCourse(@RequestBody Course course) {
        try {
            // 校验字段
            if (SportUtils.judgeNull(course.getCourseId().trim())
                    || course.getCourseId().length() > EnumValidation.FOURTY.getNum()) {
                throw new ValidationException("请输入合法的课程ID");
            }
            // 规整
            course.setCourseId(course.getCourseId().trim());
            // 执行删除
            courseService.deleteCourseById(course.getCourseId());
            result = new ReturnJson(NumEnum.SUCCESS.getIndex(), "删除数据成功！");

        } catch (ValidationException v) {
            LOGGER.error("CourseController--deleteCourse error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), v.getMessage());
        } catch (CourseException c) {
            LOGGER.error("CourseController--deleteCourse error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), c.getMessage());
        } catch (Exception e) {
            LOGGER.error("CourseController--deleteCourse error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), e.getMessage());
        }
        return result;
    }

    /**
     * 课程排序
     *
     * @param sortObject 排序key与value集合
     * @return ReturnJson 返回封装的Json对象
     */
    @RequestMapping(value = "/admin/sortCourse")
    public ReturnJson sortCourse(@RequestBody SortObject sortObject) {
        try {
            // 校验字段
            if (sortObject.getCourseName().equals("")) {
                sortObject.setCourseName(null);
            }
            if (sortObject.getCategoryName().equals("")) {
                sortObject.setCategoryName(null);
            }
            if (sortObject.getCourseTag().equals("")) {
                sortObject.setCourseTag(null);
            }
            // 校验
            if (sortObject.getSort().isEmpty()) {
                throw new ValidationException("请输入合法的排序集合！");
            }

            // 执行排序
            courseService.sortCourse(sortObject.getSort(), sortObject.getPageNum(), sortObject.getPageSize(),
                    sortObject.getCourseName(),
                    sortObject.getCategoryName(), sortObject.getCourseTag());
            result = new ReturnJson(NumEnum.SUCCESS.getIndex(), "排序成功！");

        } catch (ValidationException v) {
            LOGGER.error("CourseController--sortCourse error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), v.getMessage());
        } catch (CourseException c) {
            LOGGER.error("CourseController--sortCourse error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), c.getMessage());
        } catch (Exception e) {
            LOGGER.error("CourseController--sortCourse error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), e.getMessage());
        }
        return result;
    }

    /**
     * 上传图片
     *
     * @param request 请求对象
     * @param file    图片文件对象
     * @return ReturnJson 封装标准json
     */
    @RequestMapping(value = "/admin/uploadPicture", method = RequestMethod.POST)
    public ReturnJson uploadPicture(HttpServletRequest request, MultipartFile file) {
        String fileNameTemp = "";
        try {
            // 获取图片大小
            long size = file.getSize();
            if (size == 0) {
                // 判断文件内容是否为空
                throw new ServiceException("上传图片不能为空!");
            }
            // 限制图片大小
            if (size > EnumValidation.FIVE.getNum() * EnumValidation.MB.getNum()) {
                throw new ServiceException("请上传图片大小为5MB以下的图片!");
            }
//            // 设置上传路径
            String uploadDir = request.getSession().getServletContext().getRealPath("/") + "upload/";
            uploadDir = uploadDir.replace("/sport", "");
            uploadDir = uploadDir.replace("\\sport", "");
            System.out.println(uploadDir);
//            String uploadDir = this.getClass().getClassLoader().getResource("").getPath();
//            uploadDir = uploadDir.replace("/WEB-INF/classes/", "") + "/upload/";
//            System.out.println(uploadDir);

            File dir = new File(uploadDir);
            // 创建文件
            if (!dir.exists()) {
                dir.mkdir();
            }
            // 获取文件后缀名
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            if (".gif".equals(suffix)) {
                throw new ServiceException("图片格式不能为为gif!");
            }
            // 重新命名图片
            String filename = UUID.randomUUID() + suffix;
            File serverFile = new File(uploadDir + filename);
            // 执行保存
            file.transferTo(serverFile);
            // 图片完整路径
            fileNameTemp = uploadDir + filename;
            // 校验图片尺寸
            BufferedImage sourceImg = ImageIO.read(new FileInputStream(fileNameTemp));
            int imgWidth = sourceImg.getWidth();
            int imgHeight = sourceImg.getHeight();
            System.out.println("图片高度：" + imgHeight + " 图片宽度: " + imgWidth);

//            String projectPath = environment.getProperty("img.url") + "/upload/" + filename;
            String projectPath = "/upload/" + filename;
            result = new ReturnJson(NumEnum.SUCCESS.getIndex(), "上传成功！", projectPath);

        } catch (ServiceException s) {
            LOGGER.error("CourseController--uploadPicture error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), s.getMessage());
        } catch (NullPointerException n) {
            LOGGER.error("CourseController--uploadPicture error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), "上传失败，请检查图片是否为能正常打开的图片！");
        } catch (Exception e) {
            LOGGER.error("CourseController--uploadPicture error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), e.getMessage());
        }
        return result;

    }

    /**
     * 依据条件查询课程表
     *
     * @param selectCourse 查询相关参数对象
     * @return ReturnJson 封装标准json
     */
    @RequestMapping(value = "/admin/selectByCondition", method = RequestMethod.POST)
    public ReturnJson selectByCondition(@RequestBody SelectCourse selectCourse) {
        try {
            // 校验字段
            if (selectCourse.getCourseName().equals("")) {
                selectCourse.setCourseName(null);
            }
            if (selectCourse.getCategoryName().equals("")) {
                selectCourse.setCategoryName(null);
            }
            if (selectCourse.getCourseTag().equals("")) {
                selectCourse.setCourseTag(null);
            }
            // 判断是否需要分页
            if (selectCourse.getStatus() == 0) {
                // 设置分页
                PageHelper.startPage(selectCourse.getPageNum(), selectCourse.getPageSize());
                // 转换为分页结果
                List<Course> coursesTempPage = courseService.selectByCondition(selectCourse.getCourseName(),
                        selectCourse.getCategoryName(), selectCourse.getCourseTag());
                // 强制转换
                Page<Course> coursesPage = (Page<Course>) coursesTempPage;
                result = new ReturnJson(NumEnum.SUCCESS.getIndex(), "查询成功！", coursesPage, coursesPage.getTotal());
            } else {
                // 不分页的课程集合
                List<Course> coursesTemp = courseService.selectByCondition(selectCourse.getCourseName(),
                        selectCourse.getCategoryName(), selectCourse.getCourseTag());
                result = new ReturnJson(NumEnum.SUCCESS.getIndex(), "查询成功！", coursesTemp, coursesTemp.size());
            }

        } catch (CourseException c) {
            LOGGER.error("CourseController--selectByCondition error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), c.getMessage());
        } catch (Exception e) {
            LOGGER.error("CourseController--selectByCondition error!");
            result = new ReturnJson(NumEnum.FAIL.getIndex(), e.getMessage());
        }
        return result;
    }

}
